﻿namespace ShellNavigator.Client.Utils
{
  #region

  using System;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Windows;

  #endregion

  /// <summary>
  ///     TODO: Update summary.
  /// </summary>
  public static class UIHelper
  {
    #region Public Methods

    public static void LongOperationWithCancel<R, T>(
      R data,
      Func<CancellationToken, T> function,
      Action<R, T> onSuccess,
      Action<Exception> onError, 
      Window window)
    {
      var cancelTokenSource = new CancellationTokenSource();
      var cancelToken = cancelTokenSource.Token;
      EventHandler waitWindowOnClosed = delegate { cancelTokenSource.Cancel(); };
      window.Closed += waitWindowOnClosed;

      window.Show();

      Task.Factory.StartNew(() => function(cancelToken)).ContinueWith(
        doneTask =>
          {
            window.Close();
            window.Closed -= waitWindowOnClosed;

            if (doneTask.IsFaulted)
            {
              onError(doneTask.Exception);
            }
            else
            {
              onSuccess(data, doneTask.Result);
            }
          }, 
          TaskScheduler.FromCurrentSynchronizationContext());
    }

    #endregion
  }
}